//
//  KEGameView.swift
//  KoalaEn
//
//  Created by Wade on 2024/10/29.
//

import Foundation
import QMUIKit
import SnapKit
import UIKit

open class KEGameView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {
    var contentView: UIView?
    
    var questionBtn: QMUIButton?
    
    var collectionView: UICollectionView?
    
    var submitBtn: QMUIButton?
 
    var questionList: [KEWordsDetail]?
    
    var selectIndexPath: IndexPath?
    
    // 错误次数
    var testWrongTimes: Int = 0
    // 单词卡片
    var preBtn: UIButton?
    var nextBtn: UIButton?
    var currentGame: KEGameModel?
    var currentIndex: Int = 0
    var gameList: [KEGameModel]? {
        didSet {
            self.preBtn?.isHidden = true
            self.currentIndex = 0
            self.gameList = Array(Set<KEGameModel>(self.gameList!))
            self.currentGame = self.gameList?[self.currentIndex]
            self.questionList = self.currentGame?.questionWords
            self.reloadData()
        }
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.currentGame = self.gameList?.first
        self.setupSubViews()
    }
    
    override public init(frame: CGRect) {
        super.init(frame: frame)
        self.currentGame = self.gameList?.first
        self.setupSubViews()
    }
    
    func setupSubViews() {
        let contentView = UIView()
        self.addSubview(contentView)
        contentView.backgroundColor = .clear
        self.contentView = contentView
        contentView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        
        let questionBtn = QMUIButton()
        contentView.addSubview(questionBtn)
        questionBtn.setTitle(self.currentGame?.anwserWord?.word_en, for: .normal)
        questionBtn.titleLabel?.font = .boldSystemFont(ofSize: 40)
        questionBtn.titleLabel?.textAlignment = .center
        questionBtn.setTitleColor(.MainTextColor, for: .normal)
        questionBtn.addTarget(self, action: #selector(self.questionBtnClick), for: .touchUpInside)
        self.questionBtn = questionBtn
        questionBtn.snp.makeConstraints { make in
            make.centerX.equalTo(contentView)
            make.top.equalTo(contentView).offset(20)
            make.width.equalTo(contentView)
            make.height.equalTo(100)
        }
        self.questionBtn = questionBtn
        
        let preViewBtn = UIButton()
        preViewBtn.setImage(.init(named: "ic_pre"), for: .normal)
        contentView.addSubview(preViewBtn)
        preViewBtn.snp.makeConstraints { make in
            make.width.equalTo(40)
            make.height.equalTo(55)
            make.centerY.equalTo(questionBtn)
            make.left.equalTo(contentView).offset(10)
        }
        preViewBtn.addTarget(self, action: #selector(self.preViewBtnClick), for: .touchUpInside)
        preViewBtn.isHidden = true
        self.preBtn = preViewBtn
        
        let nextBtn = UIButton()
        nextBtn.setImage(.init(named: "ic_next"), for: .normal)
        contentView.addSubview(nextBtn)
        nextBtn.snp.makeConstraints { make in
            make.width.equalTo(40)
            make.height.equalTo(55)
            make.centerY.equalTo(questionBtn)
            make.right.equalTo(contentView).offset(-10)
        }
        nextBtn.addTarget(self, action: #selector(self.nextBtnClick), for: .touchUpInside)
        self.nextBtn = nextBtn
        
        // Create a waterfall layout
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.itemSize = CGSizeMake(160, 160)
        layout.minimumLineSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        contentView.addSubview(collectionView)
        collectionView.backgroundColor = .clear
        collectionView.snp.makeConstraints { make in
            make.left.right.equalTo(contentView)
            make.top.equalTo(questionBtn.snp.bottom).offset(30)
            make.height.equalTo(330)
        }
        collectionView.delegate = self
        collectionView.dataSource = self
        
        self.collectionView = collectionView
        self.collectionView?.register(KEGameViewAnwserCell.self, forCellWithReuseIdentifier: "KEGameViewAnwserCell")
        
        let submitBtn = QMUIButton()
        submitBtn.setTitle("确定", for: .normal)
        contentView.addSubview(submitBtn)
        submitBtn.backgroundColor = .MainBGColor
        submitBtn.setTitleColor(.white, for: .normal)
        submitBtn.layer.cornerRadius = 22
        submitBtn.clipsToBounds = true
        self.submitBtn = submitBtn
        submitBtn.addTarget(self, action: #selector(self.submitBtnClick), for: .touchUpInside)
        submitBtn.snp.makeConstraints { make in
            make.centerX.equalTo(contentView)
            make.top.equalTo(collectionView.snp.bottom).offset(30)
            make.height.equalTo(44)
            make.width.equalTo(300)
        }
    }
    
    @objc func submitBtnClick() {
        if self.currentGame?.anwserWord?.word_en == self.currentGame?.questionWords?[self.selectIndexPath?.item ?? 0].word_en {
            KEAudioManager.sharedInstance.playEn(en: "wow,Good Job!", zh: "")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                self.nextBtnClick()
            }
        } else {
            KEAudioManager.sharedInstance.playEn(en: "oh wrong!", zh: "")
            self.testWrongTimes += 1
        }
    }
    
    @objc func questionBtnClick() {
        if self.currentGame?.gameType != .wordToAudio {
            KEAudioManager.sharedInstance.playEn(en: self.currentGame?.anwserWord?.word_en ?? "", zh: "")
        }
    }
    
    @objc func preViewBtnClick() {
        self.nextBtn?.isHidden = false
        self.currentIndex -= 1
        self.currentGame = self.gameList?[self.currentIndex]
        self.questionList = self.currentGame?.questionWords
        self.reloadData()
        if self.currentIndex == 0 {
            self.preBtn?.isHidden = true
        }
    }

    @objc func nextBtnClick() {
        self.preBtn?.isHidden = false
        if self.currentIndex == self.gameList!.count - 1 {
            self.nextBtn?.isHidden = true
        }else{
            self.currentIndex += 1
            self.currentGame = self.gameList?[self.currentIndex]
            self.questionList = self.currentGame?.questionWords
            self.reloadData()
        }
    }
    
    func reloadData() {
        self.submitBtn?.isHidden = true
        self.questionBtn?.imageView?.contentMode = .scaleAspectFit
        self.questionBtn?.setImage(nil, for: .normal)
        self.questionBtn?.setTitle(nil, for: .normal)
        switch self.currentGame?.gameType {
        case .imageToWords:
            self.questionBtn!.sd_setImage(with: .init(string: self.currentGame?.anwserWord?.word_iamges?.first ?? ""), for: .normal)
        case .wordToImage:
            self.questionBtn!.setTitle(self.currentGame?.anwserWord?.word_en, for: .normal)
        case .imageToAudio:
            self.submitBtn?.isHidden = false
            self.questionBtn!.sd_setImage(with: .init(string: self.currentGame?.anwserWord?.word_iamges?.first ?? ""), for: .normal)
        case .audioToimage:
            self.questionBtn!.setImage(.init(named: "ic_audio_player"), for: .normal)
        case .audioToWord:
            self.questionBtn!.setImage(.init(named: "ic_audio_player"), for: .normal)
        case .wordToAudio:
            self.submitBtn?.isHidden = false
            self.questionBtn!.setTitle(self.currentGame?.anwserWord?.word_en, for: .normal)
        default:
            print("")
        }
        self.collectionView?.reloadData()
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let list = self.currentGame?.questionWords else { return 0 }
        return list.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let list = self.currentGame?.questionWords else { return UICollectionViewCell() }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "KEGameViewAnwserCell", for: indexPath) as! KEGameViewAnwserCell
        cell.index = indexPath.item
        cell.gameType = self.currentGame?.gameType
        cell.wordDetail = self.currentGame?.questionWords?[indexPath.item]
       
        return cell
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.selectIndexPath = indexPath
        if self.currentGame?.gameType == .wordToAudio || self.currentGame?.gameType == .imageToAudio {
            KEAudioManager.sharedInstance.playEn(en: self.currentGame?.questionWords?[indexPath.item].word_en ?? "", zh: "")
         
        } else {
            if self.currentGame?.anwserWord?.word_en == self.currentGame?.questionWords?[self.selectIndexPath?.item ?? 0].word_en {
                KEAudioManager.sharedInstance.playEn(en: "wow,good Job!", zh: "")
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                    self.nextBtnClick()
                }
            } else {
                KEAudioManager.sharedInstance.playEn(en: "oh Wrong!", zh: "")
                self.testWrongTimes += 1
            }
        }
    }
}
